// 后台脚本

// API调用管理器 - 处理频率限制和重试机制
class APICallManager {
  constructor() {
    this.requestQueue = [];
    this.isProcessing = false;
    this.lastRequestTime = 0;
    this.minInterval = 1500; // 每次请求最小间隔1.5秒，考虑3次/分钟的限制
    this.retryDelays = [2000, 5000, 10000]; // 重试延迟：2秒、5秒、10秒
    this.maxRetries = 3;
  }

  // 添加请求到队列
  async enqueueRequest(requestFn, data) {
    return new Promise((resolve, reject) => {
      this.requestQueue.push({
        requestFn,
        data,
        resolve,
        reject,
        retryCount: 0
      });
      
      if (!this.isProcessing) {
        this.processQueue();
      }
    });
  }

  // 处理请求队列
  async processQueue() {
    if (this.isProcessing || this.requestQueue.length === 0) {
      return;
    }

    this.isProcessing = true;

    while (this.requestQueue.length > 0) {
      const request = this.requestQueue.shift();
      
      try {
        // 确保请求间隔
        const now = Date.now();
        const timeSinceLastRequest = now - this.lastRequestTime;
        if (timeSinceLastRequest < this.minInterval) {
          const waitTime = this.minInterval - timeSinceLastRequest;
          console.log(`等待 ${waitTime}ms 后继续请求...`);
          await this.sleep(waitTime);
        }

        console.log(`执行API请求，队列剩余: ${this.requestQueue.length}`);
        this.lastRequestTime = Date.now();
        
        const result = await request.requestFn(request.data);
        request.resolve(result);
        
      } catch (error) {
        console.error('API请求失败:', error.message);
        
        // 检查是否是频率限制错误
        if (this.isRateLimitError(error) && request.retryCount < this.maxRetries) {
          request.retryCount++;
          const retryDelay = this.retryDelays[request.retryCount - 1] || 10000;
          
          console.log(`检测到频率限制，${retryDelay/1000}秒后重试 (第${request.retryCount}次重试)`);
          
          // 重新加入队列头部
          this.requestQueue.unshift(request);
          
          // 等待重试延迟
          await this.sleep(retryDelay);
          
        } else {
          // 超过重试次数或其他错误，直接拒绝
          request.reject(error);
        }
      }
    }

    this.isProcessing = false;
  }

  // 检查是否是频率限制错误
  isRateLimitError(error) {
    const message = error.message.toLowerCase();
    return message.includes('rate limit') || 
           message.includes('rpm') || 
           message.includes('请稍后重试') ||
           message.includes('调用过于频繁') ||
           error.status === 429;
  }

  // 休眠函数
  sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
  }

  // 获取当前队列状态
  getQueueStatus() {
    return {
      queueLength: this.requestQueue.length,
      isProcessing: this.isProcessing
    };
  }
}

// 创建全局API调用管理器实例
const apiCallManager = new APICallManager();

chrome.runtime.onInstalled.addListener(() => {
  // 设置侧边栏
  chrome.sidePanel.setPanelBehavior({ openPanelOnActionClick: true });
  
  // 初始化存储（如果不存在）
  chrome.storage.local.get(['apiKey', 'isConfigured', 'model', 'maxTokens'], (result) => {
    if (!result.hasOwnProperty('apiKey')) {
      chrome.storage.local.set({
        // 向后兼容的旧配置
        apiKey: '',
        isConfigured: false,
        model: 'moonshot-v1-8k',
        maxTokens: 4000,
        autoTranslate: true,
        autoSummarize: true,
        theme: 'light',
        // 新的多服务商配置
        providers: {
          moonshot: {
            apiKey: '',
            baseUrl: 'https://api.moonshot.cn/v1',
            configured: false
          },
          openai: {
            apiKey: '',
            baseUrl: 'https://api.openai.com/v1',
            configured: false
          },
          anthropic: {
            apiKey: '',
            baseUrl: 'https://api.anthropic.com',
            configured: false
          }
        }
      });
    }
  });
});

// 处理来自content script的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  console.log('Background received message:', request);
  
  if (request.type === 'GET_SELECTION') {
    // 获取选中的文本
    chrome.tabs.query({ active: true, currentWindow: true }, async (tabs) => {
      if (chrome.runtime.lastError) {
        console.error('Tab query error:', chrome.runtime.lastError);
        sendResponse({ 
          success: false, 
          error: '无法获取当前标签页',
          text: '',
          hasSelection: false
        });
        return;
      }
      
      if (!tabs || tabs.length === 0) {
        console.error('No active tabs found');
        sendResponse({ 
          success: false, 
          error: '没有找到活动标签页',
          text: '',
          hasSelection: false
        });
        return;
      }
      
      const tab = tabs[0];
      console.log('Sending message to tab:', tab.id, tab.url);
      
      // 首先尝试通过content script获取
      chrome.tabs.sendMessage(tab.id, { type: 'GET_SELECTION' }, async (response) => {
        if (chrome.runtime.lastError) {
          console.error('Send message error:', chrome.runtime.lastError);
          console.log('Content script not available, trying executeScript...');
          
          // 备用方案：直接执行脚本获取选中文本
          try {
            const results = await chrome.scripting.executeScript({
              target: { tabId: tab.id },
              func: () => {
                try {
                  const selectedText = window.getSelection().toString().trim();
                  return {
                    success: true,
                    text: selectedText,
                    hasSelection: selectedText.length > 0
                  };
                } catch (error) {
                  return {
                    success: false,
                    error: '获取选中文本失败',
                    text: '',
                    hasSelection: false
                  };
                }
              }
            });
            
            if (results && results[0] && results[0].result) {
              console.log('executeScript result:', results[0].result);
              sendResponse(results[0].result);
            } else {
              sendResponse({ 
                success: false, 
                error: '无法执行脚本',
                text: '',
                hasSelection: false
              });
            }
          } catch (executeError) {
            console.error('executeScript error:', executeError);
            sendResponse({ 
              success: false, 
              error: '无法与页面通信',
              text: '',
              hasSelection: false
            });
          }
        } else {
          console.log('Received response from content script:', response);
          sendResponse(response);
        }
      });
    });
    return true; // 保持消息通道开放
  }
  
  if (request.type === 'GET_PAGE_CONTENT') {
    // 获取页面内容
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (chrome.runtime.lastError) {
        sendResponse({ 
          success: false, 
          error: '无法获取当前标签页',
          content: null
        });
        return;
      }
      
      if (!tabs || tabs.length === 0) {
        sendResponse({ 
          success: false, 
          error: '没有找到活动标签页',
          content: null
        });
        return;
      }
      
      chrome.tabs.sendMessage(tabs[0].id, { type: 'GET_PAGE_CONTENT' }, (response) => {
        if (chrome.runtime.lastError) {
          sendResponse({ 
            success: false, 
            error: '无法与页面通信',
            content: null
          });
        } else {
          sendResponse(response);
        }
      });
    });
    return true; // 保持消息通道开放
  }
  
  if (request.type === 'CLEAR_SELECTION') {
    // 清除页面选中状态
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      if (chrome.runtime.lastError) {
        console.error('Tab query error:', chrome.runtime.lastError);
        sendResponse({ success: false, error: '无法获取当前标签页' });
        return;
      }
      
      if (!tabs || tabs.length === 0) {
        console.error('No active tabs found');
        sendResponse({ success: false, error: '没有找到活动标签页' });
        return;
      }
      
      const tab = tabs[0];
      console.log('清除页面选中状态，发送消息到tab:', tab.id);
      
      // 发送消息给content script清除选中状态
      chrome.tabs.sendMessage(tab.id, { type: 'CLEAR_SELECTION' }, (response) => {
        if (chrome.runtime.lastError) {
          console.log('Content script not available, trying executeScript...');
          
          // 备用方案：直接执行脚本清除选中状态
          chrome.scripting.executeScript({
            target: { tabId: tab.id },
            func: () => {
              try {
                // 清除页面选中状态
                if (window.getSelection) {
                  window.getSelection().removeAllRanges();
                }
                // 清除document的选中状态
                if (document.getSelection) {
                  document.getSelection().removeAllRanges();
                }
                return { success: true };
              } catch (error) {
                console.error('清除选中状态失败:', error);
                return { success: false, error: error.message };
              }
            }
          }).then(results => {
            if (results && results[0] && results[0].result) {
              sendResponse(results[0].result);
            } else {
              sendResponse({ success: false, error: '无法执行脚本' });
            }
          }).catch(error => {
            console.error('executeScript error:', error);
            sendResponse({ success: false, error: '清除选中状态失败' });
          });
        } else {
          console.log('Content script清除选中状态响应:', response);
          sendResponse(response || { success: true });
        }
      });
    });
    return true; // 保持消息通道开放
  }
});

// 处理API调用
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'CALL_AI_API') {
    callAIAPI(request.data)
      .then(response => {
        sendResponse({ success: true, data: response });
      })
      .catch(error => {
        sendResponse({ success: false, error: error.message });
      });
    return true; // 保持消息通道开放
  }
  
  // 兼容旧的调用方式
  if (request.type === 'CALL_KIMI_API') {
    callAIAPI(request.data)
      .then(response => {
        sendResponse({ success: true, data: response });
      })
      .catch(error => {
        sendResponse({ success: false, error: error.message });
      });
    return true; // 保持消息通道开放
  }
  
  if (request.type === 'TEST_API_KEY') {
    testApiKey(request.data.apiKey)
      .then(response => {
        sendResponse({ success: true, data: response });
      })
      .catch(error => {
        sendResponse({ success: false, error: error.message });
      });
    return true; // 保持消息通道开放
  }
  
  if (request.type === 'TEST_API_CONNECTION') {
    testApiConnection(request.data)
      .then(response => {
        sendResponse({ success: true, data: response });
      })
      .catch(error => {
        sendResponse({ success: false, error: error.message });
      });
    return true; // 保持消息通道开放
  }
  
  if (request.type === 'DETECT_FREE_MODELS') {
    detectFreeModels(request.data)
      .then(response => {
        sendResponse({ success: true, models: response });
      })
      .catch(error => {
        sendResponse({ success: false, error: error.message });
      });
    return true; // 保持消息通道开放
  }
});

// 智能API调用函数
async function callAIAPI(data) {
  // 使用API调用管理器处理请求
  return await apiCallManager.enqueueRequest(async (data) => {
    const { apiKey, messages, model = 'moonshot-v1-8k', maxTokens = 4000, providers = {} } = data;
    
    console.log('callAIAPI called with:', { model, maxTokens, messagesCount: messages?.length });
    
    if (!messages || messages.length === 0) {
      console.error('消息为空');
      throw new Error('消息内容不能为空');
    }
    
    // 获取模型对应的服务商信息
    const providerInfo = getProviderInfo(model, providers);
    
    if (!providerInfo) {
      console.error('无法识别模型服务商:', model);
      throw new Error(`不支持的模型: ${model}`);
    }
    
    if (!providerInfo.apiKey) {
      console.error('API密钥未配置:', providerInfo.name);
      throw new Error(`请先配置${providerInfo.name}的API密钥`);
    }
    
    console.log('使用服务商:', providerInfo.name, '模型:', model);
    
    // 根据提供商分发请求
    switch (providerInfo.name) {
      case 'moonshot':
        // 提取系统和用户消息
        const systemMsg = messages.find(msg => msg.role === 'system')?.content || '';
        const userMsg = messages.find(msg => msg.role === 'user')?.content || '';
        return await callMoonshotAPI(providerInfo.apiKey, providerInfo.baseUrl, model, systemMsg, userMsg);
      case 'openai':
        return await callOpenAIAPI(providerInfo.apiKey, providerInfo.baseUrl, model, messages, maxTokens);
      case 'anthropic':
        return await callAnthropicAPI(providerInfo.apiKey, providerInfo.baseUrl, model, messages, maxTokens);
      default:
        throw new Error(`不支持的提供商: ${providerInfo.name}`);
    }
  }, data);
}

// 获取模型对应的服务商信息
function getProviderInfo(model, providers = {}) {
  // Moonshot及其免费模型
  if (model.startsWith('moonshot-') || 
      model.includes('kimi') || 
      model.includes('moonshot') ||
      model.includes('free-api')) {
    return {
      name: 'moonshot',
      apiKey: providers.moonshot?.apiKey,
      baseUrl: providers.moonshot?.baseUrl || 'https://api.moonshot.cn/v1'
    };
  } 
  // OpenAI模型
  else if (model.startsWith('gpt-') || model.includes('openai')) {
    return {
      name: 'openai',
      apiKey: providers.openai?.apiKey,
      baseUrl: providers.openai?.baseUrl || 'https://api.openai.com/v1'
    };
  } 
  // Anthropic模型
  else if (model.startsWith('claude-') || model.includes('anthropic')) {
    return {
      name: 'anthropic',
      apiKey: providers.anthropic?.apiKey,
      baseUrl: providers.anthropic?.baseUrl || 'https://api.anthropic.com'
    };
  }
  
  console.log(`无法识别模型服务商: ${model}`);
  return null;
}

// Moonshot API调用
async function callMoonshotAPI(apiKey, baseUrl, model, systemPrompt, userMessage) {
  console.log('调用Moonshot API:', { model, baseUrl });
  
  const response = await fetch(`${baseUrl}/chat/completions`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: model,
      messages: [
        { role: 'system', content: systemPrompt },
        { role: 'user', content: userMessage }
      ],
      temperature: 0.3,
      max_tokens: 1000
    })
  });

  return await handleAPIResponse(response, 'Moonshot');
}

// OpenAI API调用
async function callOpenAIAPI(apiKey, baseUrl, model, messages, maxTokens) {
  console.log('调用OpenAI API:', { model, baseUrl });
  
  const response = await fetch(`${baseUrl}/chat/completions`, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json'
    },
    body: JSON.stringify({
      model: model,
      messages: messages,
      temperature: 0.3,
      max_tokens: maxTokens
    })
  });

  return await handleAPIResponse(response, 'OpenAI');
}

// Anthropic API调用
async function callAnthropicAPI(apiKey, baseUrl, model, messages, maxTokens) {
  console.log('调用Anthropic API:', { model, baseUrl });
  
  // 提取系统消息和用户消息
  const systemMessage = messages.find(msg => msg.role === 'system');
  const userMessages = messages.filter(msg => msg.role !== 'system');
  
  const response = await fetch(`${baseUrl}/messages`, {
    method: 'POST',
    headers: {
      'x-api-key': apiKey,
      'Content-Type': 'application/json',
      'anthropic-version': '2023-06-01'
    },
    body: JSON.stringify({
      model: model,
      max_tokens: maxTokens,
      temperature: 0.3,
      system: systemMessage ? systemMessage.content : undefined,
      messages: userMessages
    })
  });

  // Anthropic API返回格式不同，需要特殊处理
  console.log(`Anthropic API响应状态:`, response.status, response.statusText);
  
  const responseText = await response.text();
  console.log(`Anthropic API响应内容:`, responseText);
  
  if (!response.ok) {
    try {
      const errorData = JSON.parse(responseText);
      console.error(`Anthropic API错误详情:`, errorData);
      
      let errorMessage = errorData.error?.message || `Anthropic API请求失败: ${response.status} ${response.statusText}`;
      
      // 特殊处理常见错误
      if (response.status === 404) {
        errorMessage = '模型不存在或不可用，请检查模型名称是否正确';
      } else if (response.status === 401) {
        errorMessage = 'API密钥无效或已过期，请检查密钥配置';
      } else if (response.status === 403) {
        errorMessage = '访问被拒绝，请检查API密钥权限';
      } else if (response.status === 429) {
        errorMessage = 'API调用频率超限，请稍后重试';
      } else if (response.status === 400) {
        if (errorMessage.toLowerCase().includes('model')) {
          errorMessage = '不支持该模型，请选择其他可用模型';
        }
      }
      
      throw new Error(errorMessage);
    } catch (parseError) {
      console.error('解析Anthropic错误响应失败:', parseError);
      throw new Error(`Anthropic API请求失败 (${response.status})，请检查网络连接和配置。响应内容: ${responseText.substring(0, 200)}`);
    }
  }
  
  try {
    const result = JSON.parse(responseText);
    console.log(`Anthropic API响应解析成功:`, result);
    
    if (!result.content || !result.content[0] || !result.content[0].text) {
      console.error(`Anthropic API响应格式异常:`, result);
      throw new Error(`Anthropic API响应格式异常`);
    }
    
    const content = result.content[0].text;
    console.log('提取的内容:', content);
    return content;
  } catch (parseError) {
    console.error(`解析Anthropic API响应失败:`, parseError);
    throw new Error(`解析Anthropic API响应失败: ${parseError.message}。响应内容: ${responseText.substring(0, 200)}`);
  }
}

// 通用API响应处理
async function handleAPIResponse(response, providerName) {
  console.log(`${providerName} API响应状态:`, response.status, response.statusText);
  
  const responseText = await response.text();
  console.log(`${providerName} API响应原始文本:`, responseText);
  
  if (!response.ok) {
    console.error(`${providerName} API请求失败，状态:`, response.status);
    
    try {
      const errorData = JSON.parse(responseText);
      console.error(`${providerName} API错误详情:`, errorData);
      
      let errorMessage = errorData.error?.message || `${providerName} API请求失败: ${response.status} ${response.statusText}`;
      
      // 特殊处理常见错误
      if (response.status === 404) {
        errorMessage = '模型不存在或不可用，请检查模型名称是否正确';
      } else if (response.status === 401) {
        errorMessage = 'API密钥无效或已过期，请检查密钥配置';
      } else if (response.status === 403) {
        errorMessage = '访问被拒绝，请检查API密钥权限';
      } else if (response.status === 429) {
        errorMessage = 'API调用频率超限，请稍后重试';
      } else if (response.status === 400) {
        // 检查是否是模型相关错误
        if (errorMessage.toLowerCase().includes('model')) {
          errorMessage = '不支持该模型，请选择其他可用模型';
        }
      }
      
      throw new Error(errorMessage);
    } catch (parseError) {
      console.error('解析错误响应失败:', parseError);
      
      // 根据状态码提供更好的错误信息
      let friendlyMessage = '';
      switch (response.status) {
        case 404:
          friendlyMessage = '请求的模型不存在，请检查模型配置';
          break;
        case 401:
          friendlyMessage = 'API认证失败，请检查密钥配置';
          break;
        case 403:
          friendlyMessage = '没有权限访问该API，请检查密钥权限';
          break;
        case 429:
          friendlyMessage = 'API调用过于频繁，请稍后重试';
          break;
        case 500:
          friendlyMessage = '服务器内部错误，请稍后重试';
          break;
        default:
          friendlyMessage = `API请求失败 (${response.status})，请检查网络连接和配置`;
      }
      
      throw new Error(`${friendlyMessage}。响应内容: ${responseText.substring(0, 200)}`);
    }
  }
  
  try {
    const result = JSON.parse(responseText);
    console.log(`${providerName} API响应解析成功:`, result);
    
    if (!result.choices || !result.choices[0] || !result.choices[0].message) {
      console.error(`${providerName} API响应格式异常:`, result);
      throw new Error(`${providerName} API响应格式异常`);
    }
    
    const content = result.choices[0].message.content;
    console.log('提取的内容:', content);
    return content;
  } catch (parseError) {
    console.error(`解析${providerName} API响应失败:`, parseError);
    throw new Error(`解析${providerName} API响应失败: ${parseError.message}。响应内容: ${responseText.substring(0, 200)}`);
  }
}

// 测试API密钥函数
async function testApiKey(apiKey) {
  if (!apiKey) {
    throw new Error('请先输入API密钥');
  }
  
  try {
    const response = await fetch('https://api.moonshot.cn/v1/models', {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      }
    });
    
    if (response.ok) {
      return '验证成功';
    } else {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.error?.message || `API密钥无效: ${response.status}`);
    }
  } catch (error) {
    if (error.message.includes('fetch')) {
      throw new Error('网络连接失败，请检查网络设置');
    }
    throw error;
  }
}

// 测试API连接（支持多服务商）
async function testApiConnection(data) {
  const { provider, apiKey, baseUrl } = data;
  
  if (!apiKey) {
    throw new Error('请先输入API密钥');
  }
  
  try {
    let response;
    let testEndpoint;
    let headers = {
      'Content-Type': 'application/json'
    };
    
    // 根据服务商设置不同的测试端点和请求头
    switch (provider) {
      case 'moonshot':
        testEndpoint = `${baseUrl}/models`;
        headers['Authorization'] = `Bearer ${apiKey}`;
        break;
      case 'openai':
        testEndpoint = `${baseUrl}/models`;
        headers['Authorization'] = `Bearer ${apiKey}`;
        break;
      case 'anthropic':
        // Anthropic使用不同的认证方式
        testEndpoint = `${baseUrl}/v1/messages`;
        headers['x-api-key'] = apiKey;
        headers['anthropic-version'] = '2023-06-01';
        
        // Anthropic需要POST请求来测试
        response = await fetch(testEndpoint, {
          method: 'POST',
          headers: headers,
          body: JSON.stringify({
            model: 'claude-3-haiku-20240307',
            max_tokens: 10,
            messages: [{ role: 'user', content: 'Hello' }]
          })
        });
        break;
      default:
        throw new Error(`不支持的服务商: ${provider}`);
    }
    
    // 对于非Anthropic服务商，使用GET请求测试
    if (provider !== 'anthropic') {
      response = await fetch(testEndpoint, {
        method: 'GET',
        headers: headers
      });
    }
    
    if (response.ok) {
      return '连接测试成功';
    } else {
      const errorData = await response.json().catch(() => ({}));
      throw new Error(errorData.error?.message || `连接失败: ${response.status} ${response.statusText}`);
    }
  } catch (error) {
    if (error.message.includes('fetch') || error.message.includes('TypeError')) {
      throw new Error('网络连接失败，请检查网络设置或API地址');
    }
    throw error;
  }
}

// 验证模型是否真正可用
async function verifyModelAvailability(modelId, apiKey, baseUrl) {
  try {
    console.log(`🔍 开始验证模型可用性: ${modelId}`);
    console.log(`📡 请求地址: ${baseUrl}/chat/completions`);
    
    const response = await fetch(`${baseUrl}/chat/completions`, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        model: modelId,
        messages: [
          { 
            role: 'user', 
            content: 'test' 
          }
        ],
        max_tokens: 1,
        temperature: 0.1
      })
    });
    
    console.log(`📊 模型 ${modelId} 响应状态: ${response.status} ${response.statusText}`);
    
    // 获取响应文本用于详细分析
    const responseText = await response.text();
    console.log(`📝 响应内容: ${responseText.substring(0, 300)}...`);
    
    // 检查响应状态
    if (response.status === 200) {
      // 200 表示成功，验证响应格式
      try {
        const result = JSON.parse(responseText);
        if (result.choices && result.choices[0] && result.choices[0].message) {
          console.log(`✅ 模型 ${modelId} 验证成功`);
          return true;
        } else {
          console.log(`❌ 模型 ${modelId} 响应格式异常`);
          return false;
        }
      } catch (parseError) {
        console.log(`❌ 模型 ${modelId} 响应解析失败`);
        return false;
      }
    } else if (response.status === 429) {
      // 429 表示限流，但模型存在且可用
      console.log(`⚠️ 模型 ${modelId} 当前限流，但模型可用`);
      return true;
    } else if (response.status === 400) {
      // 400 可能是参数错误，需要检查具体错误信息
      try {
        const errorData = JSON.parse(responseText);
        const errorMessage = errorData.error?.message || '';
        
        // 如果错误不是关于模型不存在，则认为模型可用
        const modelNotFoundKeywords = ['model not found', 'model does not exist', 'invalid model', 'unknown model'];
        const isModelNotFound = modelNotFoundKeywords.some(keyword => 
          errorMessage.toLowerCase().includes(keyword)
        );
        
        if (isModelNotFound) {
          console.log(`❌ 模型 ${modelId} 不存在: ${errorMessage}`);
          return false;
        } else {
          console.log(`⚠️ 模型 ${modelId} 存在但参数有误: ${errorMessage}`);
          return true; // 参数错误但模型存在
        }
      } catch (parseError) {
        console.log(`❌ 模型 ${modelId} 400错误，响应解析失败`);
        return false;
      }
    } else if (response.status === 401 || response.status === 403) {
      // 401/403 表示认证问题，但模型可能存在
      console.log(`🔐 模型 ${modelId} 认证问题，但模型可能存在`);
      return false; // 认证问题暂不认为可用
    } else if (response.status === 404) {
      // 404 表示模型不存在
      console.log(`❌ 模型 ${modelId} 不存在 (404)`);
      return false;
    } else {
      // 其他状态码，尝试解析错误信息
      try {
        const errorData = JSON.parse(responseText);
        const errorMessage = errorData.error?.message || '';
        
        // 检查错误信息中是否包含模型不支持的关键词
        const unsupportedKeywords = [
          'model not found',
          'model does not exist', 
          'invalid model',
          'unsupported model',
          'model not available',
          '不支持',
          '不存在',
          '无效模型',
          'unknown model'
        ];
        
        const isUnsupported = unsupportedKeywords.some(keyword => 
          errorMessage.toLowerCase().includes(keyword.toLowerCase())
        );
        
        if (isUnsupported) {
          console.log(`❌ 模型 ${modelId} 不受支持: ${errorMessage}`);
          return false;
        } else {
          console.log(`⚠️ 模型 ${modelId} 其他错误但可能可用: ${errorMessage}`);
          return false; // 更保守的策略，未知错误不认为可用
        }
      } catch (parseError) {
        console.log(`❌ 模型 ${modelId} 响应解析失败，状态码: ${response.status}`);
        return false;
      }
    }
    
  } catch (error) {
    console.log(`❌ 模型 ${modelId} 验证失败:`, error.message);
    return false;
  }
}

// 检测免费模型
async function detectFreeModels(data) {
  const { provider, apiKey, baseUrl } = data;
  
  try {
    let freeModels = [];
    
    switch (provider) {
      case 'moonshot':
        // 对于Moonshot，首先尝试获取官方模型列表
        try {
          console.log('正在获取Moonshot官方模型列表...');
          const response = await fetch(`${baseUrl}/models`, {
            method: 'GET',
            headers: {
              'Authorization': `Bearer ${apiKey}`,
              'Content-Type': 'application/json'
            }
          });
          
          if (response.ok) {
            const result = await response.json();
            console.log('Moonshot模型列表响应:', result);
            
            if (result.data && Array.isArray(result.data)) {
              // 查找可能的免费模型
              const freeModelPatterns = ['free', 'lite', 'mini', 'basic'];
              const detectedModels = result.data.filter(model => 
                freeModelPatterns.some(pattern => 
                  model.id.toLowerCase().includes(pattern)
                )
              );
              
              console.log('检测到的潜在免费模型:', detectedModels);
              
              // 对检测到的模型进行实际调用验证
              for (const model of detectedModels) {
                console.log(`验证模型: ${model.id}`);
                if (await verifyModelAvailability(model.id, apiKey, baseUrl)) {
                  freeModels.push({
                    id: model.id,
                    name: model.id,
                    provider: 'moonshot'
                  });
                  console.log(`✅ 验证成功: ${model.id}`);
                } else {
                  console.log(`❌ 验证失败: ${model.id}`);
                }
              }
            }
          } else {
            console.log('获取模型列表失败，状态码:', response.status);
          }
          
          // 手动测试一些已知可能存在的免费模型
          // 这些是根据实际调研得出的可能存在的免费模型名称
          const knownPossibleModels = [
            'moonshot-v1-8k',  // 有些接口可能提供免费额度
            // 避免添加不确定存在的模型名称
          ];
          
          console.log('测试已知可能的免费模型...');
          for (const modelId of knownPossibleModels) {
            // 检查是否已经在列表中
            if (freeModels.some(m => m.id === modelId)) {
              continue;
            }
            
            console.log(`验证已知模型: ${modelId}`);
            // 验证模型是否真正可用
            if (await verifyModelAvailability(modelId, apiKey, baseUrl)) {
              freeModels.push({
                id: modelId,
                name: `${modelId} (免费额度)`,
                provider: 'moonshot'
              });
              console.log(`✅ 验证成功: ${modelId}`);
            } else {
              console.log(`❌ 验证失败: ${modelId}`);
            }
          }
          
        } catch (error) {
          console.error('检测Moonshot免费模型失败:', error);
        }
        break;
        
      case 'openai':
        // OpenAI通常没有免费模型，但可以检测试用额度模型
        try {
          console.log('正在获取OpenAI模型列表...');
          const response = await fetch(`${baseUrl}/models`, {
            method: 'GET',
            headers: {
              'Authorization': `Bearer ${apiKey}`,
              'Content-Type': 'application/json'
            }
          });
          
          if (response.ok) {
            const result = await response.json();
            if (result.data && Array.isArray(result.data)) {
              // 查找可能的免费或试用模型
              const possibleFreeModels = result.data.filter(model => 
                model.id.includes('free') || 
                model.id.includes('trial') ||
                model.id === 'gpt-3.5-turbo' // GPT-3.5有时有免费额度
              );
              
              // 验证这些模型
              for (const model of possibleFreeModels) {
                if (await verifyModelAvailability(model.id, apiKey, baseUrl)) {
                  freeModels.push({
                    id: model.id,
                    name: model.id,
                    provider: 'openai'
                  });
                }
              }
            }
          }
        } catch (error) {
          console.error('检测OpenAI免费模型失败:', error);
        }
        break;
        
      case 'anthropic':
        // Anthropic通常没有免费模型，但可以检查试用模型
        // Claude目前主要是付费模型，但可能有试用额度
        console.log('Anthropic当前没有免费模型可检测');
        freeModels = []; // 暂时不添加免费模型
        break;
    }
    
    console.log(`${provider} 最终检测到的免费模型:`, freeModels);
    return freeModels;
  } catch (error) {
    console.error('检测免费模型失败:', error);
    return [];
  }
}

// 改进的错误处理函数
function createDetailedRateLimitError(errorData) {
  // 提取更具体的频率限制信息
  if (errorData.error?.message?.includes('RPM')) {
    const rpmMatch = errorData.error.message.match(/max RPM: (\d+)/);
    const waitMatch = errorData.error.message.match(/after (\d+) seconds?/);
    const rpm = rpmMatch ? rpmMatch[1] : '未知';
    const waitTime = waitMatch ? waitMatch[1] : '几';
    return `API调用过于频繁，您的账户每分钟最多可调用${rpm}次。请等待${waitTime}秒后重试，系统将自动为您重试。`;
  } else {
    return 'API调用频率超限，系统将自动重试，请稍候...';
  }
} 